<script lang="ts">
	import { handleReqMounted } from '@/hooks/handleReq';
	import Button from '@smui/button';
	import DaliyOrder from './_com/DaliyOrder.svelte';

	let date = new Date();

	// const weekNames = ['日', '一', '二', '三', '四', '五', '六'];
	const weekNames = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];

	$: currentYear = date.getFullYear();
	$: currentMonth = date.getMonth();

	$: firstDayOfNextMonth = new Date(currentYear, currentMonth, 1);
	$: lastDayOfNextMonth = new Date(currentYear, currentMonth + 1, 0);

	$: dates_in_month = Array.from(
		{ length: new Date(currentYear, currentMonth + 1, 0).getDate() },
		(_, i) => new Date(currentYear, currentMonth, i + 2).toISOString().substring(5, 10)
	);

	// 计算下个月的第一天是星期几
	$: firstDayWeekday = firstDayOfNextMonth.getDay();

	// 创建一个包含空白的数组，以便对齐日期
	$: emptyDays = Array.from({ length: firstDayWeekday }, () => '');

	// onMount(() => {
	// 	// 获取日历元素
	// 	const calender = document.querySelector('.calender') as HTMLElement;
	// 	const header = document.querySelector('.header') as HTMLElement;
	// 	const weekdays = document.querySelector('.weekdays') as HTMLElement;
	// 	const days = document.querySelector('.days') as HTMLElement;

	// 	getPlanList();
	// });

	// Define the type for each item
	interface Item {
		id: number;
		webType: number;
		title: string;
		code: string;
		dash: string | null; // dash can be a string or null
		ship_at: string; // assuming this is an ISO date string
		created_at: string; // assuming this is a date string
	}

	// Define the type for the etaData and createData properties
	interface DateItems {
		[date: string]: Item[]; // maps date strings to arrays of Item
	}
	// Define the main structure
	interface DataStructure {
		etaData: DateItems; // mapping of shipping dates to items
		createData: DateItems; // mapping of creation dates to items
		current_month?: string; // current month in YYYY-MM format
	}

	const getUrl = () => {
		const month = date.getMonth() + 1;
		const year = date.getFullYear();
		const url = '/plan/list?month=' + month + '&year=' + year;
		// TODO: 获取计划列表
		// await alova.Get(url, { cacheFor: 0 });
		return url;
	};
	// const params = { cacheFor: 0 };
	let currentMonthOrdersMsg: DataStructure = { createData: {}, etaData: {} }; // 当前月份订单信息
	let createDaysCheckList: string[] = [];
	let deleteDaysCheckList: string[] = [];
	const handle = (res: any) => {
		if (res && res.createData) {
			currentMonthOrdersMsg = res as DataStructure;
			const { createData, etaData } = res;
			createDaysCheckList = Object.keys(createData).map((i) => i.substring(5));
			deleteDaysCheckList = Object.keys(etaData).map((i) => i.substring(5));
		}
	};
	const { loading, reqInfo } = handleReqMounted(getUrl, {
		type: 'get',
		handle
	});

	// 定义一个数组，包含月份的英文名称
	const monthNames = [
		'January',
		'February',
		'March',
		'April',
		'May',
		'June',
		'July',
		'August',
		'September',
		'October',
		'November',
		'December'
	];

	const lastMonth = () => (date = new Date(currentYear, currentMonth - 1, 1)) && reqInfo(true);
	const nextMonth = () => (date = new Date(currentYear, currentMonth + 1, 1)) && reqInfo(true);

	let daliyOrderRef: any = null; // 日订单对话框
	const open = (date: string) =>
		(deleteDaysCheckList.includes(date) || createDaysCheckList.includes(date)) &&
		daliyOrderRef?.init(date, [
			Object.entries(currentMonthOrdersMsg.createData).find(([key]) => key.includes(date))?.[1] ||
				[],
			Object.entries(currentMonthOrdersMsg.etaData).find(([key]) => key.includes(date))?.[1] || []
		]);
</script>

<!-- 未来计划 -->
<div class="calender-wrap flex-cc">
	<!-- 做一个日历表 -->
	<div class="w-1320px max-w-100% min-w-350px calender p-3 flex flex-col gap-1">
		<div class="header flex flex-row">
			<Button class="left material-icons" on:click={lastMonth}>chevron_left</Button>
			<div class="relative flex-1 h-36px line-height-36px text-center border-none! font-size-21px">
				<span>{monthNames[currentMonth] + ' / ' + currentYear}</span>
			</div>
			<Button class="right material-icons" on:click={nextMonth}>chevron_right</Button>
		</div>
		<div class="weekdays">
			{#each weekNames as weekday}
				<div class="weekday flex-cc">{weekday}</div>
			{/each}
		</div>
		<div class="days">
			{#each emptyDays as _}
				<div class="day-empty flex-cc empty"></div>
				<!-- 空白格子 -->
			{/each}
			{#each dates_in_month as date}
				<button class="day relative cursor-pointer flex-cc" on:click={() => open(date)}>
					<span>{date.replace('-', ' - ')}</span>
					{#if $loading}
						<div class="loader absolute bottom-10px left-50%"></div>
					{/if}
					{#if createDaysCheckList.includes(date)}
						<span class="block absolute bottom-10px left-10px w-20px h-20px bg-blue-7"></span>
					{/if}
					{#if deleteDaysCheckList.includes(date)}
						<span class="block absolute bottom-10px right-10px w-20px h-20px bg-red-7"></span>
					{/if}
				</button>
			{/each}
		</div>
	</div>

	<DaliyOrder bind:this={daliyOrderRef} />
</div>

<style lang="scss">
	.calender {
		background-color: var(--color-white);
		border-radius: 8px;

		.weekdays,
		.days {
			display: grid;
			grid-template-columns: repeat(7, 1fr);
			gap: 0.25rem;
		}

		.weekdays {
			height: 40px;
			line-height: 40px;
			background-color: var(--mdc-theme-primary);
			color: var(--color-white);
			border: 1px solid var(--border-color);
			font-weight: bolder;
		}

		.day {
			background-color: var(--color-bg-gray);
			border: 1px solid var(--border-color);
			aspect-ratio: 1 / 1;
		}
		.day-empty {
			aspect-ratio: 1 / 1;
		}
		.hover {
			background-color: var(--mdc-theme-primary) !important;
			color: var(--color-white) !important;
		}
	}

	/* HTML: <div class="loader"></div> */
	.loader {
		width: 20px;
		aspect-ratio: 1;
		background: var(--mdc-theme-primary);
		box-shadow: 0 0 60px 15px var(--mdc-theme-primary);
		clip-path: inset(0);
		transform: translateX(calc(-50% - 40px));
		animation:
			l4-1 0.5s ease-in-out infinite alternate,
			l4-2 1s ease-in-out infinite;
	}
	@keyframes l4-1 {
		100% {
			transform: translateX(40px);
		}
	}
	@keyframes l4-2 {
		33% {
			clip-path: inset(0 0 0 -100px);
		}
		50% {
			clip-path: inset(0 0 0 0);
		}
		83% {
			clip-path: inset(0 -100px 0 0);
		}
	}
</style>
